<template>
  <div ref="mapContainer" class="content"></div>
</template>

<script>
import * as zymap from '../zymap.min.js'
import data from "@/assets/demoData/changshadayuecheng20211207.json";

export default {
  name: "routeMap",
  data() {
    return {
      zymap: null,
      openList: undefined,//待遍历的分类数据
      checkTheType: undefined,//查看类型
      mapPath: [],//路网数据
    }
  },
  // components:{DownOutlined},
  mounted() {

    this.$nextTick(() => {
      this.initMapPath();
      this.initMap();
    })
  },

  methods: {

    /**
     * 初始化地图
     */
    initMap() {
      this.zymap = new zymap.ZYMap({
        serverUrl: 'http://map.malllead.com',
        buildingCode: '0001-000H-0005',
        container: this.$refs.mapContainer,
        floorCode: '0001-000H-0005-0002',
        viewMode: '2d',
        token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIxMDAxMDAwMSIsImV4cCI6MTY0MDY3MzQwOX0.yPaFn-mN72lEgstnMbrP224wzyeOaN_CYN6K5oxNtcg'
      })
      console.log('zymap', this.zymap)
      this.zymap.on('floorChanged', this.afterFloorChange.bind(this))
    },
    afterFloorChange() {
      this.addLines()
    },
    /**
     * 分类
     */
    fnGenderClassification(data, type) {
      let newList = [];
      for (const datum of data) {
        const sex = datum.sex;
        if (sex == type) {
          newList.push(datum);
        }
      }
      return newList;
    },
    /**
     * 格式化路网数据
     */
    initMapPath() {
      //获取基础数据
      let mapPath = this.getDefaultMapPath();
      const points = mapPath.points;
      const paths = mapPath.paths;
      let vertexMap = [];
      for (const point of points) {
        //当前点关联的点
        let neighborList = [];
        for (const path of paths) {
          const pathStart = path.start;
          const pathEnd = path.end;
          const length = path.length;
          if (pathStart == point.id) {
            neighborList.push({
              id: pathEnd,
              length
            })
          } else if (pathEnd == point.id) {
            neighborList.push({
              id: pathStart,
              length
            })
          }
        }
        vertexMap.push({
          id: point.id,//路径ID
          neighborList,//当前节点关联的节点
        })
      }
      this.mapPath = vertexMap;
    },
    /**
     * 获取基础路网数据
     * @returns {{paths: {}, points: {}}}
     */
    getDefaultMapPath() {
      const mapPath = require('@/assets/demoData/path.json');
      const points = mapPath.points;
      const paths = mapPath.paths;
      return {points, paths}
    },
    /**
     * 获取完整的路径
     */
    getPath(data) {
      //路网原始数据
      const defaultMapPath = this.getDefaultMapPath()
      //经过处理的数据，包括节点ID和相邻节点
      const mapPath = this.mapPath;

      /**
       * 数据合并
       */
      function dataMerge(networkData) {
        let path = [];
        for (const networkDatum of networkData) {
          console.log('networkDatum====1', networkDatum)
          //如果路径为空
          if (path.length == 0) {
            path.push(networkDatum)
          } else {
            for (let i = 0; i < path.length; i++) {
              let pathElement = path[i]
              console.log('pathElement2', pathElement)
              const startId = pathElement[pathElement.length - 1].id;
              const endId = networkDatum[0].id;
              //检查俩点是否相连
              const d = fnWhetherOrNotConnected(startId, endId)
              //是否已添加
              const isAdd = fnWhetherToAdd(pathElement, endId)
              console.log('是否添加', isAdd, '是否相连', d, i)
              if (d && !isAdd) {
                console.log('添加')
                for (const networkDatumElement of networkDatum) {
                  pathElement.push(networkDatumElement)
                }
                break;
              }
              // else if (i == path.length - 1) {
              //   path.push(networkDatum.map((item) => {
              //     return {
              //       x: item.x, y: item.y, id: item.id
              //     }
              //   }))
              // }
              // console.log('是否相连4==========================', d)
            }

          }
        }
        return path;
      }

      function isInclude(aa, bb) {
        return aa.every((item) => {
          return bb.some((sub) => {
            return sub.id === item.id;
          });
        });
      }

      function fnWhetherToAdd(arr, id) {
        for (const arrElement of arr) {
          if (arrElement.id == id) {
            return true;
          }
        }
      }

      /**
       * 判断是否相连
       * @param start 起点
       * @param end 终点
       */
      function fnWhetherOrNotConnected(start, end) {
        console.log('fnWhetherOrNotConnected-start', start, 'end', end)
        let openList = [];//待遍历的数组
        let closedList = [];//已遍历的数组
        openList.push(start)
        while (openList.length > 0) {
          // console.log('openList====', openList)
          let smallest = openList.pop();
          if (smallest == end) {
            return true
          }
          closedList.push(smallest);
          //获取当前节点坐标
          const node = fnFindTheCurrentNode(smallest);
          // console.log('node==-==', node)
          if (node != undefined) {
            //获取当前节点的临近节点
            const neighborList = node.neighborList
            //遍历相邻节点
            for (const neighborListElement of neighborList) {
              //相邻节点ID
              let id = neighborListElement.id;
              if (closedList.indexOf(id) == -1 && openList.indexOf(id) == -1) {
                //将相邻节点id添加到待遍历数组
                openList.push(id);
              }
            }
          }
        }
      }

      /**
       * 查找当前节点
       * @param nodeId 节点ID
       * @returns {*}
       */
      function fnFindTheCurrentNode(nodeId) {
        for (const mapPathElement of mapPath) {
          if (mapPathElement.id == nodeId) {
            return mapPathElement;
          }
        }
      }

      /**
       * 根据坐标获取路网数据
       */
      function getPoint(descCurrent) {
        for (const point of defaultMapPath.points) {
          if (point.x == descCurrent.x && point.y == descCurrent.y) {
            return point;
          }
        }
      }

      /**
       * 转换成路网数据
       */
      function convertToRoadNetworkData() {
        let openList = []
        while (data.length > 0) {
          const current = data.pop();
          // console.log('current==============',current)
          //当前路段数组
          let item = [];
          for (const point of current.points) {
            //根据当前点获取路网的数据
            const currentPoint = getPoint(point);
            // console.log('currentPoint==================',currentPoint)
            item.push(currentPoint);
          }
          openList.push(item);
        }
        return openList;
      }

      let path = [];
      //获取路网数据
      let networkData = convertToRoadNetworkData();
      // console.log('networkData=============',networkData)
      //分类数据
      // path = dataMerge(networkData);
      return networkData;
    },
    addLines() {
      const data = require('@/assets/demoData/changshadayuecheng20211207.json')
      // console.log('data=================',data)
      let lines = this.fnGenderClassification(data, 0);
      // console.log('boyList========================',boyList)
      // const lines = this.getPath(boyList);
      console.log('lines', lines)
      for (const line of lines) {
        const line2 = new zymap.ZYLineMarker({
          segments: line,
          width: 3, //线宽
          color: '#2f54eb',
          height: 200
        })
        line2.addTo(this.zymap)
      }
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
html, body {
  width: 100vw;
  height: 100vh;
  padding: 0;
  margin: 0 !important;
  position: relative;
  overflow: hidden;
}

.content {
  width: 100vw;
  height: 100vh;
  flex-shrink: 1;
  position: relative;
  box-sizing: border-box;
}
</style>
